<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="customerName" label="客户姓名">
          <el-input
            v-model="queryParams.customerName"
            placeholder="客户姓名"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="merchantName" label="商家名称">
          <el-input
            v-model="queryParams.merchantName"
            placeholder="商家名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item prop="orderStatus" label="订单状态">
          <el-input
            v-model="queryParams.orderStatus"
            placeholder="订单状态"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <i-ep-search />
            搜索
          </el-button>
          <el-button @click="businessQuery">
            <i-ep-refresh />
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="openDialog()">
          <i-ep-plus />
          新增
        </el-button>
        <el-button
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
        >
          <i-ep-delete />
          删除
        </el-button>
      </template>
      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="orderList"
        highlight-current-row
        border
      >
        <el-table-column
          label="订单日期"
          prop="orderDate"
          width="250"
          align="center"
        />
        <el-table-column
          label="客户姓名"
          prop="customerName"
          width="150"
          align="center"
        />
        <el-table-column
          label="客户邮箱"
          prop="customerEmail"
          width="150"
          align="center"
        />
        <el-table-column
          label="订单状态"
          prop="orderStatus"
          width="150"
          align="center"
        >
          <template #default="scope">
            <el-tag v-if="scope.row.orderStatus === 'ACTIVE'" type="success"
              >正常</el-tag
            >
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="商家名称" prop="merchantName" min-width="100" />
        <el-table-column
          label="订单总金额"
          prop="totalAmount"
          width="150"
          align="center"
        />
        <el-table-column
          label="创建时间"
          prop="createdTime"
          width="200"
          align="center"
        />
        <el-table-column
          label="修改时间"
          prop="updatedTime"
          width="200"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              link
              @click="openDialog(scope.row.id)"
            >
              <i-ep-edit />
              编辑
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <i-ep-delete />
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="businessFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="客户姓名" prop="customerName">
          <el-input v-model="formData.customerName" placeholder="客户姓名" />
        </el-form-item>
        <el-form-item label="客户邮箱" prop="customerEmail">
          <el-input v-model="formData.customerEmail" placeholder="客户邮箱" />
        </el-form-item>
        <el-form-item label="商家id" prop="merchantId">
          <el-input v-model="formData.merchantId" placeholder="商家id" />
        </el-form-item>
        <el-form-item label="订单总金额" prop="totalAmount">
          <el-input v-model="formData.totalAmount" placeholder="订单总金额" />
        </el-form-item>
        <el-form-item label="订单状态" prop="orderStatus">
          <el-select v-model="formData.orderStatus">
            <el-option :key="0" label="正常" :value="'ACTIVE'" />
            <el-option :key="1" label="禁用" :value="'DISABLED'" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getOrderPage } from "@/api/order/index";
import { OrderQuery, OrderPageVO, OrdersForm } from "@/api/order/type";

import { addBusiness, deleteBusinesss, updateBusiness ,getBusinessForm } from "@/api/order";

const businessFormRef = ref(ElForm);
const ids = ref<number[]>([]);

/** 关闭表单弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

const formData = reactive<OrdersForm>({
  id: undefined,
});

const rules = reactive({
  customerName: [
    { required: true, message: "请输入客户名称", trigger: "blur" },
  ],
  merchantId: [
    { required: true, message: "请输入id", trigger: "blur" },
  ],
  customerEmail: [{ required: true, message: "请输入邮箱", trigger: "blur" }],
  contactPhone: [
    { required: true, message: "请输入联系人电话", trigger: "blur" },
  ],
  totalAmount: [{ required: true, message: "请输入订单总金额", trigger: "blur" }],
  orderStatus: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

function resetForm() {
  businessFormRef.value.resetFields();
  businessFormRef.value.clearValidate();

  // formData.id = undefined;
  // formData.status = undefined;
}

const dialog = reactive({
  title: "",
  visible: false,
});
defineOptions({
  name: "Order",
  inheritAttrs: false,
});

const dateTimeRange = ref(undefined);
const queryFormRef = ref(ElForm);

const loading = ref(false);
const total = ref(0);

const queryParams = reactive<OrderQuery>({
  pageNum: 1,
  pageSize: 10,
});

const orderList = ref<OrderPageVO[]>();

/** 查询 */
function handleQuery() {
  loading.value = true;
  getOrderPage(queryParams)
    .then(({ data }) => {
      orderList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 重置查询 */
function businessQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  dateTimeRange.value = undefined;
  handleQuery();
}

onMounted(() => {
  handleQuery();
});

function handleSubmit() {
  businessFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const Id = formData.id;
      if (Id) {
        updateBusiness(Id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            businessQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addBusiness(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            businessQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function openDialog(roleId?: number) {
  dialog.visible = true;
  if (roleId) {
    dialog.title = "修改订单";
    getBusinessForm(roleId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增订单";
  }
}

function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    deleteBusinesss(roleIds)
      .then(() => {
        ElMessage.success("删除成功");
        businessQuery();
      })
      .finally(() => (loading.value = false));
  });
}
</script>
